<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Entity_Post extends Core_Db_Entity {

	protected $_relatedPosts = null;
	
	public function __construct() {
		parent::__construct(App::db());
		$this->setBaseTable('post');
	}
	
	protected function _beforeSave() {
		// when user set status null
		if ($this->hasData('status') && $this->getData('status') < 1)
			$this->setData('status', NULL);

		// convert field to boolean
		if ($this->hasData('is_visible'))
			$this->setData('is_visible', !!$this->getData('is_visible'));

		// set creation & update time
		if (!$this->getId()) $this->setCreatedTime(date('Y-m-d H:i:s'));
		$this->setUpdateTime(date('Y-m-d H:i:s'));
	}
	
	public function _beforeDelete() {
		// delete record in post_tag
		$this->_conn->query("DELETE FROM post_tag WHERE post_id={$this->getId()}");
		return $this;
	}
	
	public function validate() {
		// perform validate
		$config = array(
			array(
				'field'   => 'title',
				'label'   => 'Title',
				'rules'   => 'required'
			),
			array(
				'field'   => 'content',
				'label'   => 'Content',
				'rules'   => 'required'
			),
			array(
				'field'   => 'category',
				'label'   => 'Category',
				'rules'   => 'required'
			)
		);

		$validator = App::lib('form_validation'); 
		$validator->set_rules($config);
		//return $validator->run();
		
		if ($validator->run() == FALSE) {
			App::objectSingleton('Entity_Session_Admin')->addError($validator->getErrors());
			throw new Exception();
		};
		
		return true;
	}

	public function saveTags($data) {
		$tags = preg_split("/\s*,\s*/", strtolower($data));
		$tagIds = $this->getTagIds(); 	// get current tags of post
		$inputTags = array();

		foreach($tags as $t) {
			$tagName = $t;
			if (empty($tagName)) continue;
			
			$tag = App::object('Entity_Tag');
			$tag->loadByName($tagName);	// load tag by id
			
			// create new tag
			if (!$tag->getId()) {
				$tag->setName($tagName);
				$tag->save();
			}

			// if is new tag, add to post
			if (!in_array($tag->getId(), $tagIds)) $this->addTag($tag);
			$inputTags[] = $tag->getId();
		}

		// remove old tag that not choosed by user
		$removes = array_diff($tagIds, $inputTags);
		if (!empty($removes)) $this->removeTags($removes);
		return $this;
	}
	
	public function addTags($data) {
		$tags = preg_split("/\s*,\s*/", strtolower($data));
		$tagIds = $this->getTagIds(); 	// get current tags of post

		foreach($tags as $t) {
			$tagName = $t;
			if (empty($tagName)) continue;
			
			$tag = App::object('Entity_Tag');
			$tag->loadByName($tagName);	// load tag by id
			
			// create new tag
			if (!$tag->getId()) {
				$tag->setName($tagName);
				$tag->save();
			}

			// if is new tag, add to post
			if (!in_array($tag->getId(), $tagIds)) $this->addTag($tag);
		}

		return $this;
	}
	
	public function getTags() {
		if (!$this->getId()) return array();
		return App::object('Entity_Tag')->getCollection()->addPostFilter($this->getId());
	}

	public function addTag($tag) {
		if (!$this->getId()) return $this;
		$this->_conn->query("INSERT INTO post_tag(post_id, tag_id) VALUES({$this->getId()}, {$tag->getId()})");
		return $this;
	}
	
	public function removeTags($ids) {
		if (!$this->getId()) return $this;
		$ids = implode(',', $ids);
		$this->_conn->query("DELETE FROM post_tag WHERE post_id={$this->getId()} AND tag_id IN ({$ids})");
		return $this;
	}
	
	public function getTagIds() {
		if (!$this->getId()) return array();
		$res = array();
		$query = $this->_conn->query("SELECT tag_id FROM post_tag WHERE post_id={$this->getId()}");
		foreach($query->result_array() as $r)
			$res[] = $r['tag_id'];
		return $res;
	}
	
	public function saveImages($data) {
		$images = json_decode($data, true);
		foreach($images as $img) {
			$e = App::object('Entity_Image')->load($img['id']);
			if (!$e->getId()) {
				continue;
				//throw new Exception('Post image nolonger exists.');
			}
			
			if ($img['remove']) {
				// delete image file
				unlink($e->getFileName());
				// delete database record
				$e->delete();
			} else {
				$e->setSortOrder($img['sort_order']);
				$e->setPostId($this->getId());
				$e->save();
			}
		}
	}
	
	public function getGalleryImages() {
		if (!$this->getId()) return array();
		return App::object('Entity_Image')->getCollection()->addPostFilter($this->getId());
	}
	
	public function getRelatedPosts() {
		if (!$this->_relatedPosts) {
			$catId = $this->getCategory();
			if (!empty($catId)) {
				$this->_relatedPosts = $this->getCollection()->addCategoryFilter($catId);
				$this->_relatedPosts->getSelect()->where("post.id != {$this->getId()}");
			} else {
				$this->_relatedPosts = array();
			}
		}
		return $this->_relatedPosts;
	}
	
	public function getPostUrl() {
		return App::url('post/view', array('id' => $this->getId()));
	}
}